package com.hhf.riceshopping.seckill.scheduled;

import com.hhf.riceshopping.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * 秒杀商品的定时上架的服务
 *
 * 每天晚上 3点上架最近三天需要秒杀的商品
 */
@Slf4j
@Service
public class SeckillSkuScheduled {


    @Autowired
    SeckillService seckillService;

    @Autowired
    RedissonClient redissonClient;

    private  final String  upload_lock = "seckill:upload:lock";

    //使用分布式锁来锁住定时任务
//    @Scheduled(cron = "0 * * * * ?")  //任意小时任意整点每分钟执行一次
    //    @Scheduled(cron = "0 0 3 * * ?") 线上模式
    @Scheduled(cron = "*/3 * * * * ?")  //每隔3秒执行一次上架功能
    public void uploadSeckillSkuLatest3Days(){
        log.info("上架的秒杀商品信息....");
        //分布式锁
        RLock lock = redissonClient.getLock(upload_lock);
        lock.lock();
        try {
            seckillService.uploadSeckillSkuLatest3Days();
        }finally {
            //还在持有锁的状态，并且是当前线程持有的锁再解锁
            if (lock.isLocked() && lock.isHeldByCurrentThread()){
                lock.unlock();
            }

        }

    }

}
